package com.example.ymm.modules1.service.impl.user;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSON;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.ymm.base.BaseServiceImpl;
import com.example.ymm.exception.YmException;
import com.example.ymm.model.CommonResult;
import com.example.ymm.model.TableList;
import com.example.ymm.model.UserLogin;
import com.example.ymm.model.YmPageDto;
import com.example.ymm.modules1.entity.hl.yw.YwApprove;
import com.example.ymm.modules1.entity.hl.yw.YwDept;
import com.example.ymm.modules1.entity.hl.yw.YwMoneyAffirmLog;
import com.example.ymm.modules1.entity.ms.DEmployee;
import com.example.ymm.modules1.entity.my.sys.SysApprovalSetting;
import com.example.ymm.modules1.entity.my.sys.SysApprovalSettingLine;
import com.example.ymm.modules1.entity.my.sys.SysApprovalSettingNode;
import com.example.ymm.modules1.entity.my.user.*;
import com.example.ymm.modules1.mapper.my.user.DbApprovalLogMapper;
import com.example.ymm.modules1.query.DbApprovalLogQueryCriteria;
import com.example.ymm.modules1.query.DbApprovalNodeQueryCriteria;
import com.example.ymm.modules1.query.hl.YwMoneyAffirmLogQueryCriteria;
import com.example.ymm.modules1.service.dd.ms.DingNoticeService;
import com.example.ymm.modules1.service.dd.ms.DingWaitService;
import com.example.ymm.modules1.service.dto.heng.*;
import com.example.ymm.modules1.service.dto.ms.MsMoneyAffirmDto;
import com.example.ymm.modules1.service.hl.YwApproveService;
import com.example.ymm.modules1.service.hl.YwMoneyAffirmLogService;
import com.example.ymm.modules1.service.hl.YwUserService;
import com.example.ymm.modules1.service.ms.DEmployeeService;
import com.example.ymm.modules1.service.sys.SysApprovalSettingLineService;
import com.example.ymm.modules1.service.sys.SysApprovalSettingService;
import com.example.ymm.modules1.service.user.*;
import com.example.ymm.util.*;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
@DSTransactional
@DS("slave2")
@Slf4j
public class DbApprovalLogServiceImpl extends BaseServiceImpl<DbApprovalLogMapper, DbApprovalLog> implements DbApprovalLogService {

    @Autowired
    FileUtil fileUtil;
    @Autowired
    YwApproveService ywApproveService;
    @Autowired
    SysApprovalSettingService sysApprovalSettingService;

    @Autowired
    SysApprovalSettingLineService sysApprovalSettingLineService;

    @Autowired
    YwUserService ywUserService;

    @Autowired
    DbUserService dbUserService;
    @Autowired
    private DbApprovalNodeService dbApprovalNodeService;
    @Value("${spring.profiles.active}")
    private String PD_MATCH;
    @Autowired
    DbCommentService dbCommentService;

    @Autowired
    DbUserWaitService dbUserWaitService;
    @Autowired
    DingNoticeService dingNoticeService;
    @Autowired
    YwMoneyAffirmLogService ywMoneyAffirmLogService;
    @Autowired
    DingWaitService dingWaitService;
    @Autowired
    DEmployeeService dEmployeeService;


    @Override
    public TableList<DbApprovalLog> list(DbApprovalLogQueryCriteria criteria, YmPageDto pageDto) {
        IPage<DbApprovalLog> page = new Page<DbApprovalLog>(pageDto.getPage(),pageDto.getPageSize());
        QueryWrapper predicate = QueryHelpPlus.getPredicate(DbApprovalLog.class, criteria);
        predicate.orderByDesc("create_time");
        baseMapper.selectPage(page, predicate);
        TableList<DbApprovalLog> tableList=new TableList(page);
        List<DbApprovalLog> list = tableList.getList();
        list.forEach(item->{
            if(item.getStatus()==1){
                String[] split = item.getAllNodeIds().split(",");
                if(UtilValidate.isNotEmpty(item.getCurrentNodeId())){
                    if(item.getCurrentNodeId().equals(split[0])){
                        item.setIsCancel(1);
                    }
                }
            }
        });
        return tableList;
    }

    public List<DbApprovalLog> queryAll(DbApprovalLogQueryCriteria criteria) {
        List<DbApprovalLog> result =baseMapper.selectList(QueryHelpPlus.getPredicate(DbApprovalLog.class, criteria));
        return result;
    }


    @Override
    public DbApprovalLog getApproveNo(String approveNo) {
        DbApprovalLogQueryCriteria criteria=new DbApprovalLogQueryCriteria();
        criteria.setApproveNo(approveNo);
        List<DbApprovalLog> dbApprovalLogs = queryAll(criteria);
        if(dbApprovalLogs.size()>0){
            return dbApprovalLogs.get(0);
        }
        return null;
    }


    @Override
    public ApprovalCreateViewDto approvalCreateView( String approvalName,String title) {
        String userName=getUserName();
        String userRole = getUserRole();
        if ("manage".equals(userRole)) {
            userName ="刘庆峰";
        }

       // DbUser dbUser = dbUserService.findByUserName(userName);
        DEmployee dEmployee = ywUserService.getUserInfoToSlave2(userName);
        DynamicDataSourceContextHolder.clear();
        DynamicDataSourceContextHolder.push("slave2");
        SysApprovalSetting approvalSetting = sysApprovalSettingService.findByApprovalName(approvalName);
        String approvalSettingId = approvalSetting.getApprovalSettingId();
        SysApprovalSettingLine line=getMatchingApprovalLines(approvalSettingId,dEmployee,title);
        List<SysApprovalSettingNode> items = line.getItems();
        List<DbApprovalNode> nodes = new ArrayList<>();
        boolean is_first=false;//是否第一个审批人
        for(int i=0; i<items.size(); i++){
            SysApprovalSettingNode item=items.get(i);

            DbApprovalNode dbApprovalNode = new DbApprovalNode();

            dbApprovalNode.setUserId(item.getUserId());
            dbApprovalNode.setUserName(item.getUserName());
            dbApprovalNode.setApproverType(item.getApproverType());
            dbApprovalNode.setApprovalSettingNodeId(item.getApprovalSettingNodeId());
            dbApprovalNode.setSort(item.getSort());
            dbApprovalNode.setStatus(0);
            if(item.getApproverType()==1&&!is_first){
                dbApprovalNode.setStatus(1);
                is_first=true;
            }
            nodes.add(dbApprovalNode);
        }
        ApprovalCreateViewDto dto=new ApprovalCreateViewDto();
        dto.setNodes(nodes);
        return dto;
    }

    @Override
    public String approvalSubmit(String approveNo, String approvalName, YwBaseCreateDto dto) {

        String userName=getUserName();
        String userRole = getUserRole();
        if ("manage".equals(userRole)) {
            userName ="刘庆峰";
        }

        UserLogin userLogin = getUserLogin();
//        DbUser dbUser = dbUserService.findByUserName(userName);
        DEmployee dEmployee = dEmployeeService.getUserInfo(userName);;
//        DynamicDataSourceContextHolder.clear();
//        DynamicDataSourceContextHolder.push("slave2");
//        throw new YmException("测试");

        SysApprovalSetting approvalSetting = sysApprovalSettingService.findByApprovalName(approvalName);
        String approvalSettingId = approvalSetting.getApprovalSettingId();
        DbApprovalLog dbApprovalLog = new DbApprovalLog();
        dbApprovalLog.setApprovalSettingId(approvalSettingId);
        dbApprovalLog.setApproveNo(approveNo);
        dbApprovalLog.setStatus(1);
        dbApprovalLog.setUserId(userLogin.getId());
        dbApprovalLog.setUserName(userLogin.getUserName());
        dbApprovalLog.setPageName(approvalName);
        dbApprovalLog.setTitle(UtilValidate.isNotEmpty(dto.getTitle())?dto.getTitle():approvalName);
        //文件上传
        if(UtilValidate.isNotEmpty(dto.getFile())){
           String path = fileUtil.uploadImgToLocal(dto.getFile());
            dbApprovalLog.setFileUrl(path);
        }
        dbApprovalLog.setFileDataJson(dto.getFileDataJson());
        saveOrUpdate(dbApprovalLog);
        dbApprovalLog.setDeptName(dEmployee.getDname());
        dbApprovalLog.setDeptNo(dEmployee.getDtid());
        SysApprovalSettingLine line=getMatchingApprovalLines(approvalSettingId,dEmployee,dto.getTitle());

        List<String> approverUserIds=new ArrayList<>();//审批人id
        List<String> approverUserNames=new ArrayList<>();
        List<String> allUserIds=new ArrayList<>();//参与人id
        List<String> allUserNames=new ArrayList<>();//参与人名称

        List<String> approverNodeIds=new ArrayList<>();//当前审批节点ids
        List<String> allNodeIds=new ArrayList<>();//所有的审批节点

        List<SysApprovalSettingNode> items = line.getItems();
        List<DbApprovalNode> nodes = new ArrayList<>();
        String currentUserId=null;//当前审批人

        String currentUserName=null;//当前审批人名称参与人名字
        boolean is_first=false;//是否第一个审批人
        for(int i=0; i<items.size(); i++){
            SysApprovalSettingNode item=items.get(i);
            allUserIds.add(item.getUserId());
            allUserNames.add(item.getUserName());

            String tnodeId= IdUtil.getSnowflake().nextId()+"";
            //审批类型：1审批人 2知会人
            if(item.getApproverType()==1){
                approverUserIds.add(item.getUserId());
                approverUserNames.add(item.getUserName());
                approverNodeIds.add(tnodeId);
            }
            DbApprovalNode dbApprovalNode = new DbApprovalNode();

            dbApprovalNode.setApprovalNodeId(tnodeId);
            dbApprovalNode.setUserId(item.getUserId());
            dbApprovalNode.setUserName(item.getUserName());
            dbApprovalNode.setApproverType(item.getApproverType());
            dbApprovalNode.setApprovalLogId(dbApprovalLog.getApprovalLogId());
            dbApprovalNode.setApprovalSettingNodeId(item.getApprovalSettingNodeId());
            dbApprovalNode.setSort(item.getSort());
            dbApprovalNode.setStatus(0);
            allNodeIds.add(tnodeId);
            if(item.getApproverType()==1&&!is_first){
                dbApprovalNode.setStatus(1);
                currentUserId=item.getUserId();
                currentUserName=item.getUserName();
                is_first=true;

                //插入代办
                DbUserWait wait=new DbUserWait();
                wait.setApproveNo(approveNo);
                wait.setPage(dbApprovalLog.getPageName());
                wait.setUserId(item.getUserId());
                wait.setUserName(item.getUserName());
                wait.setCreateUserName(userLogin.getUserName());
                wait.setApprovalNodeId(dbApprovalNode.getApprovalNodeId());
                wait.setTitle("您有一个"+approvalName+"待处理!");

                //当前审批数据
                dbApprovalLog.setCurrentNodeId(tnodeId);

                dbUserWaitService.saveOrUpdate(wait);
                //发送消息
                if (!"dev".equals(PD_MATCH)) {
                    dingNoticeService.approvaWaitNotice(wait,approvalSetting);
                    String description="请前往钉钉控制台>全员>MS二次开发 处理";
                    JSONObject todo = dingWaitService.createTodo(wait, approvalSetting, description);
                    if(UtilValidate.isNotEmpty(todo)){
                        wait.setDdWaitId(todo.getString("id"));
                        dbUserWaitService.saveOrUpdate(wait);
                    }
                }


            }
            nodes.add(dbApprovalNode);

        }
        //是否包含创建人
        boolean is_c_create_user=false;
        for(int i=0; i<allUserIds.size(); i++){
            String s = allUserIds.get(i);
            if(s.equals(dbApprovalLog.getUserId())){
                is_c_create_user=true;
            }
        }
        if(!is_c_create_user){
            allUserIds.add(dbApprovalLog.getUserId());
            allUserNames.add(dbApprovalLog.getUserName());
        }

        dbApprovalNodeService.saveOrUpdateBatch(nodes);
        if(approverUserIds.size()>0){
            String join = String.join(",", approverUserIds);
            dbApprovalLog.setApproverUserIds(join);
        }
        if(approverUserNames.size()>0){
            String join = String.join(",", approverUserNames);
            dbApprovalLog.setApproverUserNames(join);
        }
        if(allUserIds.size()>0){
            String join = String.join(",", allUserIds);
            dbApprovalLog.setAllUserIds(join);
        }
        if(allUserNames.size()>0){
            String join = String.join(",", allUserNames);
            dbApprovalLog.setAllUserNames(join);
        }
        if(approverNodeIds.size()>0){
            String join = String.join(",", approverNodeIds);
            dbApprovalLog.setApproverNodeIds(join);
        }
        if(allNodeIds.size()>0){
            String join = String.join(",", allNodeIds);
            dbApprovalLog.setAllNodeIds(join);
        }
        dbApprovalLog.setCurrentUserId(currentUserId);
        dbApprovalLog.setCurrentUserName(currentUserName);
        saveOrUpdate(dbApprovalLog);

        YwApprove byApproveNo = ywApproveService.findByApproveNo(approveNo);
        if(UtilValidate.isNotEmpty(byApproveNo)){
            byApproveNo.setApprovalLogId(dbApprovalLog.getApprovalLogId());
            ywApproveService.saveOrUpdate(byApproveNo);
        }
        //插入评论
        DbComment dbComment=new DbComment();
        dbComment.setNote(approvalName);
        dbComment.setUserId(userLogin.getId());
        dbComment.setUserName(userLogin.getUserName());
        String comment="发起审批";
        if(UtilValidate.isNotEmpty(dto.getFile())){
            comment+=":上传附件 <a  href="+dbApprovalLog.getFileUrl()+" target=\"_blank\">"+dto.getFile().getOriginalFilename()+"</a>";
        }
        dbComment.setComment(comment);
        dbComment.setDataId(dbApprovalLog.getApprovalLogId());
        dbCommentService.saveOrUpdate(dbComment);
        return dbApprovalLog.getApprovalLogId();
    }


    @Override
    public ApprovalCreateViewDto approvalLogView(String approveNo, String approvalName) {
        DbApprovalLog approvalLog = getApproveNo(approveNo);
        if(UtilValidate.isEmpty(approvalLog)){
            throw new YmException("数据有误！");
        }
        DbApprovalNodeQueryCriteria criteria=new DbApprovalNodeQueryCriteria();
        criteria.setApprovalLogId(approvalLog.getApprovalLogId());
        List<DbApprovalNode> dbApprovalNodes = dbApprovalNodeService.queryAll(criteria);
        ApprovalCreateViewDto dto=new ApprovalCreateViewDto();
        dto.setNodes(dbApprovalNodes);
        return dto;
    }

    /**
     * 获取匹配链路
     * @return
     */
    public SysApprovalSettingLine getMatchingApprovalLines(String approvalSettingId,DEmployee dEmployee,String title){
        List<SysApprovalSettingLine> lines = sysApprovalSettingLineService.findByApprovalSettingId(approvalSettingId);
        SysApprovalSettingLine line=null;

        //匹配链路
        for(SysApprovalSettingLine line_item : lines){
            //链路类型:0无条件 1有条件
            if(line_item.getLineType()==0){
                line=line_item;
                break;
            }else if(line_item.getLineType()==1){
                //条件匹配
                //发起类型:1个人 2部门 3其他条件进入此处
                if(line_item.getConditionType()==1){
                    //标题是否匹配
                    if(UtilValidate.isNotEmpty(line_item.getTitleInclude())){
                        if(UtilValidate.isNotEmpty(title)
                                && title.contains(line_item.getTitleInclude())
                                && line_item.getConditionNo().contains(dEmployee.getTid())
                        ){
                            line=line_item;
                            break;
                        }
                    }else{
                        if(line_item.getConditionNo().contains(dEmployee.getTid())){
                            line=line_item;
                            break;
                        }
                    }
                }else if(line_item.getConditionType()==2){
                    if(line_item.getConditionNo().contains(dEmployee.getDtid())){
                        line=line_item;
                        break;
                    }
                }else if(line_item.getConditionType()==3){
                    line=line_item;
                    break;
                }
            }
        }
        if(UtilValidate.isEmpty(line)){
            throw new YmException("无匹配条件!");
        }

        return line;
    }


    @Override
    public void approvalCancel(String approveNo,String approvalName) {
        DbApprovalLog approvalLog = getApproveNo(approveNo);
        if(UtilValidate.isEmpty(approvalLog)){
            throw new YmException("数据有误！");
        }
        if(approvalLog.getStatus()>1){
            throw new YmException("该审批已完结！");
        }
        String approverNodeIds = approvalLog.getApproverNodeIds();
        String s = approverNodeIds.split(",")[0];
        DbApprovalNode first_node = dbApprovalNodeService.getById(s);
        if(first_node.getStatus()>1){
            throw new YmException("当前审批正在进行中，无法撤回！");
        }
        approvalLog.setStatus(0);
        saveOrUpdate(approvalLog);
        //插入评论
        DbComment dbComment=new DbComment();
        dbComment.setNote(approvalName);
        dbComment.setUserId(approvalLog.getUserId());
        dbComment.setUserName(approvalLog.getUserName());
        dbComment.setComment("撤回审批");
        dbComment.setDataId(approvalLog.getApprovalLogId());
        dbCommentService.saveOrUpdate(dbComment);
        //第一个审批节点处理
        first_node.setStatus(0);
        dbApprovalNodeService.saveOrUpdate(first_node);
        //通知
        ApproverMsgNotifyDto dto=new ApproverMsgNotifyDto();
        dto.setApproveNo(approveNo);
        dto.setApproverName(approvalName);
        dto.setUserName(first_node.getUserName());
        dto.setCreateUserName(approvalLog.getUserName());
        dto.setUserId(first_node.getUserId());
        SysApprovalSetting approvalNameSetting = sysApprovalSettingService.findByApprovalName(approvalName);
        dto.setApprovalNameSetting(approvalNameSetting);
        dingNoticeService.approvalCancelNotice(dto);

        //代办撤销
        DbUserWait wait = dbUserWaitService.findByApprovalNodeId(first_node.getApprovalNodeId());
        dingWaitService.finishTodo(wait);
        if(UtilValidate.isNotEmpty(wait)){
            dbUserWaitService.removeById(wait);
        }

    }

    @Override
    public void approvalPass(YwApprovaPassDto dto,String approvalName) {
        String approveNo=dto.getApproveNo();

        DbApprovalLog approvalLog = getApproveNo(approveNo);
        if(UtilValidate.isEmpty(approvalLog)){
            throw new YmException("数据有误！");
        }
        SysApprovalSetting approvalSetting = sysApprovalSettingService.findByApprovalName(approvalName);
        if(UtilValidate.isEmpty(approvalSetting)){
            throw new YmException("请联系管理员配置审批！");
        }
        String userName=getUserName();
        String userRole = getUserRole();
        if ("manage".equals(userRole)) {
            userName ="刘庆峰";
        }
//        DbUser dbUser = dbUserService.findByUserName(userName);
        String ids = approvalLog.getApproverNodeIds();
        String[] split1 = ids.split(",");
        List<String> idList = new ArrayList<>(Arrays.asList(split1));


        String allNodeIds = approvalLog.getAllNodeIds();
        String[] allNodeIdArr= allNodeIds.split(",");
        //当前节点处理进程

        DbApprovalNode currentNode = dbApprovalNodeService.getById(approvalLog.getCurrentNodeId());
        currentNode.setStatus(2);
        currentNode.setComment(dto.getComment());
        Timestamp now = new Timestamp(System.currentTimeMillis());
        currentNode.setPassTime(now);
        dbApprovalNodeService.saveOrUpdate(currentNode);

        dbUserWaitService.completeUserWait(approvalLog.getCurrentNodeId());

        //插入评论
        DbComment dbComment=new DbComment();
        dbComment.setNote(approvalName);
        dbComment.setUserId(currentNode.getUserId());
        dbComment.setUserName(currentNode.getUserName());
        String comment ="同意";
        if(UtilValidate.isNotEmpty(dbComment.getComment())){
            comment="同意:"+comment;
        }
        dbComment.setComment(comment);
        dbComment.setDataId(approvalLog.getApprovalLogId());
        dbCommentService.saveOrUpdate(dbComment);

        //下一个节点处理进程
        idList.remove(0);
        //还有没有审批节点
        if(idList.size()>0){
            //下一个 节点 id 不一定是审批节点哦
            Integer t_index=null;
            for(int i=0;i<allNodeIdArr.length;i++){
                String currentNodeId = allNodeIdArr[i];
                if(approvalLog.getCurrentNodeId().equals(currentNodeId)){
                    t_index=i;
                }
            }
//            String next_node=null;
//            if(t_index<allNodeIdArr.length-1){
//                 next_node=allNodeIdArr[t_index-1];
//            }else if(t_index==allNodeIdArr.length-1){
//                 //没有下一个节点了
//            }
//            //下一个审批节点id
//            String next_approval_id = idList.get(0);
            ApproverMsgNotifyDto msgNotify=new ApproverMsgNotifyDto();
            msgNotify.setApproveNo(approvalLog.getApproveNo());
            msgNotify.setApproverName(approvalName);
            msgNotify.setCreateUserName(approvalLog.getUserName());
            msgNotify.setApprovalNameSetting(approvalSetting);
            DbApprovalNode next_approvalNode=for_each_next_node(t_index,allNodeIdArr,msgNotify);
            //下一个审批节点处理
//            DbApprovalNode next_approvalNode = dbApprovalNodeService.getById(next_approval_id);
            if(UtilValidate.isNotEmpty(next_approvalNode)){
                next_approvalNode.setStatus(1);
                dbApprovalNodeService.saveOrUpdate(next_approvalNode);
                approvalLog.setCurrentNodeId(next_approvalNode.getApprovalNodeId());
                approvalLog.setCurrentUserName(next_approvalNode.getUserName());
                approvalLog.setCurrentUserId(next_approvalNode.getUserId());
                saveOrUpdate(approvalLog);
                //待办
                //插入代办
                DbUserWait wait=new DbUserWait();
                wait.setApproveNo(approveNo);
                wait.setPage(approvalLog.getPageName());
                wait.setUserId(next_approvalNode.getUserId());
                wait.setUserName(next_approvalNode.getUserName());
                wait.setCreateUserName(approvalLog.getUserName());
                wait.setApprovalNodeId(next_approvalNode.getApprovalNodeId());
                wait.setTitle("您有一个"+approvalName+"待处理!");
                dbUserWaitService.saveOrUpdate(wait);


                //发消息
                if (!"dev".equals(PD_MATCH)) {
                    dingNoticeService.approvaWaitNotice(wait,approvalSetting);
                    try {
                        String page=approvalSetting.getPage();
                        String description="请前往钉钉控制台>全员>MS二次开发 处理";
                        JSONObject todo = dingWaitService.createTodo(wait, approvalSetting, description);
                        if(UtilValidate.isNotEmpty(todo)){
                            wait.setDdWaitId(todo.getString("id"));
                            dbUserWaitService.saveOrUpdate(wait);
                        }
                    }catch (Exception e){
                        log.error(e.getMessage(),e);
                    }
                }
               //

            }else{
                //没有，就全部完成了
                approvalLog.setCurrentNodeId("");
                approvalLog.setCurrentUserName("");
                approvalLog.setCurrentUserId("");
                approvalLog.setStatus(2);
                approvalLog.setPassTime(new Date());
                saveOrUpdate(approvalLog);
                //发送审批通过消息
                dingNoticeService.approvaAllPassNotice(approvalLog,dto.getComment(),approvalSetting);
                //全部通过的后续处理
                approvaAllPassFn(approveNo,approvalName,approvalLog);
            }
        }else{
            //没有，就全部完成了
            approvalLog.setCurrentNodeId("");
            approvalLog.setCurrentUserName("");
            approvalLog.setCurrentUserId("");
            approvalLog.setStatus(2);
            approvalLog.setPassTime(new Date());
            saveOrUpdate(approvalLog);
            //发送审批通过消息
            dingNoticeService.approvaAllPassNotice(approvalLog,dto.getComment(),approvalSetting);
            //全部通过的后续处理
            approvaAllPassFn(approveNo,approvalName,approvalLog);
        }

    }

    /**
     * 全部通过的审批后续处理
     * 如推送薪福通
     */
    public void approvaAllPassFn(String approveNo,String approvalName,DbApprovalLog approvalLog){
//        Thread thread=new Thread(()->{
//
//        });
//        thread.start();
        if("配送费审批".equals(approvalName)){
            YwApprove approve = ywApproveService.findByApproveNo(approveNo);
            if(UtilValidate.isNotEmpty(approve)){
                JSONArray objects = ywApproveService.importJsonDataPeiSong(approve, approvalName, approvalLog);
                if(UtilValidate.isNotEmpty(objects)){
                    JSONObject jsonObject = objects.getJSONObject(0);
                    if(jsonObject.containsKey("errorMessage")&&UtilValidate.isNotEmpty(jsonObject.getString("errorMessage"))){
                        EmailUtil.sendEmail("1055162826@qq.com","推送 配送费审批 到鑫福通失败:"+approveNo,jsonObject.getString("errorMessage"));

                    }
                }
            }
        }
    }

    /**
     * 测试推送薪福通
     */
    @Override
    public void testApprovaAllPassFn(){
        String approveNo="PSF_20251010090341122000";
        DbApprovalLog approvalLog = getApproveNo(approveNo);
        approvaAllPassFn(approveNo,"配送费审批",approvalLog);
    }

    @Override
    public void for_each_test() {
        Integer t_index=0;
        String ids="1,2,3,4,5";
        String[] allNodeIdArr = ids.split(",");
        DbApprovalNode next_approvalNode=for_each_next_node(t_index,allNodeIdArr,new ApproverMsgNotifyDto());
        System.out.println(next_approvalNode);
    }

    public DbApprovalNode  for_each_next_node(Integer t_index, String[] allNodeIdArr, ApproverMsgNotifyDto dto){
//        String next_node=null;
        if(t_index+1<allNodeIdArr.length-1){
            t_index=t_index+1;
            String next_node=allNodeIdArr[t_index];
            DbApprovalNode node = dbApprovalNodeService.getById(next_node);
            //知会人
            if(node.getApproverType()==2){
                dto.setUserId(node.getUserId());
                dto.setUserName(node.getUserName());
                //通知知会人
                dingNoticeService.approvaJoinNotice(dto);
                node.setStatus(2);
                dbApprovalNodeService.saveOrUpdate(node);
//                System.out.println("---通知只会人"+node.getUserName());

                return for_each_next_node(t_index,allNodeIdArr,dto);
            }else{
               return node;
            }
        }
        else {
            String next_node=allNodeIdArr[allNodeIdArr.length-1];
            DbApprovalNode node = dbApprovalNodeService.getById(next_node);
            //知会人
            if(node.getApproverType()==2){
                dto.setUserId(node.getUserId());
                dto.setUserName(node.getUserName());
                //通知知会人
                 dingNoticeService.approvaJoinNotice(dto);
                node.setStatus(2);
                dbApprovalNodeService.saveOrUpdate(node);
//                System.out.println("---通知只会人"+node.getUserName());
            }else{
                return null;
            }
        }
        return null;

    }

    @Override
    public void approvalBack(YwApprovaPassDto dto,String approvalName) {
        String approveNo=dto.getApproveNo();

        DbApprovalLog approvalLog = getApproveNo(approveNo);
        if(UtilValidate.isEmpty(approvalLog)){
            throw new YmException("数据有误！");
        }
        String userName=getUserName();
        String userRole = getUserRole();
        if ("manage".equals(userRole)) {
            userName ="刘庆峰";
        }

        //当前节点处理进程

        DbApprovalNode currentNode = dbApprovalNodeService.getById(approvalLog.getCurrentNodeId());
        currentNode.setStatus(99);
        currentNode.setComment(dto.getComment());
        Timestamp now = new Timestamp(System.currentTimeMillis());
        currentNode.setPassTime(now);
        dbApprovalNodeService.saveOrUpdate(currentNode);
//        DbUser dbUser = dbUserService.findByUserName(userName);
        approvalLog.setStatus(99);
        approvalLog.setCurrentNodeId("");
        approvalLog.setCurrentUserName("");
        approvalLog.setCurrentUserId("");
        saveOrUpdate(approvalLog);

        YwMoneyAffirmLogQueryCriteria c2=new YwMoneyAffirmLogQueryCriteria();
        c2.setApproveNo(approveNo);
        List<YwMoneyAffirmLog> ywMoneyAffirmLogs = ywMoneyAffirmLogService.queryAll(c2);
        ywMoneyAffirmLogs.forEach(ywMoneyAffirmLog -> {
            ywMoneyAffirmLog.setOrderNo(ywMoneyAffirmLog.getOrderNo()+"已驳回");
        });
        ywMoneyAffirmLogService.saveOrUpdateBatch(ywMoneyAffirmLogs);

        DbApprovalNodeQueryCriteria criteria=new DbApprovalNodeQueryCriteria();
        criteria.setApprovalLogId(approvalLog.getApprovalLogId());
        criteria.setStatus(1);

        String comment="驳回";
        if(!currentNode.getUserName().equals(userName)){
            comment=userName+"替"+currentNode.getUserName()+"驳回";
        }
        if(UtilValidate.isNotEmpty(dto.getComment())){
            comment+=":"+dto.getComment();
        }
        //插入评论
        DbComment dbComment=new DbComment();
        dbComment.setNote(approvalName);
        dbComment.setUserId(currentNode.getUserId());
        dbComment.setUserName(currentNode.getUserName());
        dbComment.setComment(comment);
        dbComment.setDataId(approvalLog.getApprovalLogId());
        dbCommentService.saveOrUpdate(dbComment);
        //完成代办
//        DbUserWait wait = dbUserWaitService.findByApprovalNodeId(currentNode.getApprovalNodeId());
//        wait.setStatus(1);
//        dbUserWaitService.saveOrUpdate(wait);
        dbUserWaitService.completeUserWait(currentNode.getApprovalNodeId());

        SysApprovalSetting approvalNameSetting = sysApprovalSettingService.findByApprovalName(approvalName);
        //通知
        dingNoticeService.approvaBackNotice(approvalLog,comment,userName,approvalNameSetting);
    }

    @Override
    public ApprovalButtonShowDto approveButtonShow(String approveNo) {
        String userName=getUserName();
        String userRole = getUserRole();
        DbApprovalLog approvalLog = getApproveNo(approveNo);
        if(UtilValidate.isEmpty(approvalLog)){
            throw new YmException("数据有误！");
        }
        ApprovalButtonShowDto dto=new ApprovalButtonShowDto();
        boolean currentApprovalShow = false;
        boolean canAgainCreateShow= false;
        if(approvalLog.getStatus()==1){
            if ("manage".equals(userRole)) {
                currentApprovalShow = true;
            }
            if (approvalLog.getCurrentUserName().contains(userName)) {
                currentApprovalShow = true;
            }
        }
        if(approvalLog.getStatus()==99||approvalLog.getStatus()==0){
            if (approvalLog.getUserName().contains(userName)) {
                //判断是否在当月
                Date now = new Date();
                Date create=new Date(approvalLog.getCreateTime().getTime());
                String s1 = DateKit.dateFormat(now, "yyyy-MM");
                String s2 = DateKit.dateFormat(create, "yyyy-MM");
                if(s1.equals(s2)){
                    canAgainCreateShow = true;
                }
            }
//            canAgainCreateShow = true;
        }
        dto.setCurrentApprovalShow(currentApprovalShow);
        dto.setCanAgainCreateShow(canAgainCreateShow);
        return dto;
    }


    @Override
    public TableList<DbApprovalLog> ywDeptTotalList(DbApprovalLogQueryCriteria criteria, YmPageDto pageDto) {
        getPage(pageDto);
        criteria.setPageName("业务员提成审批");
        List<DbApprovalLog> dbApprovalLogs = baseMapper.ywDeptTotalList(criteria);
        PageInfo<DbApprovalLog> pageInfo = new PageInfo<>(dbApprovalLogs);
        TableList<DbApprovalLog> tableList=new TableList(pageInfo);
        return tableList;
    }

    @Override
    public void applyUserChange(List<String> deptNoIn, String oldUserName, String newUserName,String approveNo) {
        DynamicDataSourceContextHolder.clear();
        DynamicDataSourceContextHolder.push("master");
        DbUser oldUser = dbUserService.findByUserName(oldUserName);
        DbUser newUser = dbUserService.findByUserName(newUserName);
        DynamicDataSourceContextHolder.clear();
        DynamicDataSourceContextHolder.push("slave2");
        DbApprovalLogQueryCriteria criteria=new DbApprovalLogQueryCriteria();
        if(UtilValidate.isNotEmpty(approveNo)){
            criteria.setApproveNo(approveNo);
        }else{
            criteria.setDeptNoIn(deptNoIn);
        }

        criteria.setStatus(1);
        List<DbApprovalLog> dbApprovalLogs = queryAll(criteria);
        List<DbApprovalNode> changeNodes = new ArrayList<>();
        List<DbApprovalLog> changeLogs = new ArrayList<>();
        for (DbApprovalLog dbApprovalLog : dbApprovalLogs) {

            String allUserIds = dbApprovalLog.getAllUserIds();
            String allUserNames = dbApprovalLog.getAllUserNames();
            String s = allUserIds.replaceAll(oldUser.getUserId(), newUser.getUserId());
            String s1 = allUserNames.replaceAll(oldUser.getUserName(), newUser.getUserName());
            dbApprovalLog.setAllUserNames(s1);
           // System.out.println("---dbApprovalLog:"+dbApprovalLog.getApprovalLogId());
            dbApprovalLog.setAllUserIds(s);
          //  System.out.println("---dbApprovalLog:setAllUserIds:"+s);
            changeLogs.add(dbApprovalLog);
            DbApprovalNodeQueryCriteria c2=new DbApprovalNodeQueryCriteria();
            c2.setApprovalLogId(dbApprovalLog.getApprovalLogId());
            c2.setUserName(oldUserName);
            List<DbApprovalNode> dbApprovalNodes = dbApprovalNodeService.queryAll(c2);
            if(UtilValidate.isNotEmpty(dbApprovalNodes)){
//                System.out.println("----getApprovalLogId:"+dbApprovalLog.getApprovalLogId());
//                System.out.println( "---dbApprovalNodes.size:"+dbApprovalNodes.size());
                DbApprovalNode approvalNode = dbApprovalNodes.get(0);
                approvalNode.setUserId(newUser.getUserId());
                approvalNode.setUserName(newUserName);
                changeNodes.add(approvalNode);
            }
        }
        saveOrUpdateBatch(changeLogs);
        dbApprovalNodeService.saveOrUpdateBatch(changeNodes);
//        System.out.println("----changeLogs:"+changeLogs);
//        System.out.println("---changeNodes.size:"+changeNodes);
    }


    @Override
    public void testChangeUser1() {
        List<String> deptNoIn=new ArrayList<>();
        deptNoIn.add("HL02-1");
        String oldUserName="许毅坚"; String newUserName="庄嫚艺";
        this.applyUserChange(deptNoIn,oldUserName,newUserName,"");
    }
    @Override
    public void testChangeUser2() {

        String oldUserName="许毅坚"; String newUserName="庄嫚艺";
        this.applyUserChange(null,oldUserName,newUserName,"YW_20250613110016844008");
    }


    @Override
    public String getPassApproveNoByUserName(DbApprovalLogQueryCriteria criteria) {
        return baseMapper.getPassApproveNoByUserName(criteria);
    }


    @Override
    public void sendOemPriceToHhm(List<SubmitXftDataDto> arr) {
        List<SubmitXftDataDto> results=new ArrayList<>();
        for (SubmitXftDataDto dto : arr) {
            if(dto.getDeptName().equals("OEM营销部")){
                if(dto.getUserType().equals("ji_jing")){//基金
                    results.add(dto);
                }
                if(dto.getUserType().equals("xiang_mu_group")){//项目组
                    results.add(dto);
                }
            }
        }
        System.out.println("--发送给 黄惠敏:"+ JSONObject.toJSONString(results));
        String userName = getUserName();
        if(UtilValidate.isNotEmpty(results)){
            dingNoticeService.sendOemYwPrice(results,userName);
        }


    }
}
